import { request } from '@umijs/max';
import type { GamePlatform } from './typings';

/**
 * 游戏平台管理员 API 服务
 */

// ============= 认证相关 =============

/** 管理员登录 POST /auth/login */
export async function adminLogin(body: GamePlatform.AdminLoginParams, options?: { [key: string]: any }) {
  return request<{
    code: number;
    message: string;
    data: {
      accessToken: string;
      refreshToken: string;
      tokenType: string;
      user: any;
    };
  }>('/auth/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    data: {
      identifier: body.username || body.identifier,
      password: body.password,
      rememberMe: body.rememberMe || false
    },
    ...(options || {}),
  });
}

/** 获取当前管理员信息 GET /user/profile */
export async function getCurrentAdmin(options?: { [key: string]: any }) {
  return request<{
    code: number;
    message: string;
    data: GamePlatform.AdminUser;
  }>('/user/profile', {
    method: 'GET',
    ...(options || {}),
  });
}

/** 管理员退出登录 POST /auth/logout */
export async function adminLogout(options?: { [key: string]: any }) {
  return request<{
    code: number;
    message: string;
    data: string;
  }>('/auth/logout', {
    method: 'POST',
    ...(options || {}),
  });
}

// ============= 实名认证审核 =============

/** 获取待审核的实名认证列表 GET /verification/admin/identity/pending */
export async function getIdentityVerifications(
  params: {
    page?: number;
    size?: number;
    status?: 'PENDING' | 'APPROVED' | 'REJECTED';
    keyword?: string;
  },
  options?: { [key: string]: any },
) {
  return request<{
    code: number;
    message: string;
    data: GamePlatform.IdentityVerification[];
  }>('/verification/admin/identity/pending', {
    method: 'GET',
    params: {
      ...params,
    },
    ...(options || {}),
  });
}

/** 审核实名认证 POST /verification/admin/identity/review */
export async function reviewIdentityVerification(
  id: number,
  body: {
    action: 'APPROVE' | 'REJECT';
    rejectReason?: string;
  },
  options?: { [key: string]: any }
) {
  // 转换为后端期望的格式
  const reviewData = {
    verificationId: id,
    status: body.action === 'APPROVE' ? 'APPROVED' : 'REJECTED',
    reason: body.rejectReason || ''
  };

  return request<{
    code: number;
    message: string;
    data: string;
  }>('/verification/admin/identity/review', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    data: reviewData,
    ...(options || {}),
  });
}

/** 获取实名认证详情（通过用户查询接口实现）GET /verification/identity */
export async function getIdentityVerificationDetail(
  id: number,
  options?: { [key: string]: any }
) {
  // 注意：后端没有专门的管理员查看详情接口，这里可能需要其他方案
  return request<{
    code: number;
    message: string;
    data: GamePlatform.IdentityVerification;
  }>(`/verification/identity`, {
    method: 'GET',
    ...(options || {}),
  });
}

// ============= 代练师认证审核 =============

/** 获取代练师认证列表 GET /verification/admin/trainer/pending */
export async function getTrainerCertifications(
  params: {
    page?: number;
    size?: number;
    status?: 'PENDING' | 'APPROVED' | 'REJECTED';
    keyword?: string;
  },
  options?: { [key: string]: any },
) {
  return request<{
    code: number;
    message: string;
    data: GamePlatform.TrainerCertification[];
  }>('/verification/admin/trainer/pending', {
    method: 'GET',
    params: {
      ...params,
    },
    ...(options || {}),
  });
}

/** 审核代练师认证 POST /verification/admin/trainer/review */
export async function reviewTrainerCertification(
  id: number,
  body: {
    action: 'APPROVE' | 'REJECT';
    rejectReason?: string;
  },
  options?: { [key: string]: any }
) {
  // 注意：后端使用的是 verificationId，不是 certificationId
  const reviewData = {
    verificationId: id,
    status: body.action === 'APPROVE' ? 'APPROVED' : 'REJECTED',
    reason: body.rejectReason || ''
  };

  return request<{
    code: number;
    message: string;
    data: string;
  }>('/verification/admin/trainer/review', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    data: reviewData,
    ...(options || {}),
  });
}

/** 获取代练师认证详情 GET /verification/trainer */
export async function getTrainerCertificationDetail(
  id: number,
  options?: { [key: string]: any }
) {
  return request<{
    code: number;
    message: string;
    data: GamePlatform.TrainerCertification;
  }>(`/verification/trainer`, {
    method: 'GET',
    ...(options || {}),
  });
}

// ============= 提现审核 =============

/** 获取待审核的提现申请列表 GET /verification/admin/transfer/pending */
export async function getWithdrawals(
  params: {
    page?: number;
    size?: number;
    status?: 'PROCESSING' | 'SUCCESS' | 'FAIL' | 'CANCELLED';
    keyword?: string;
    startDate?: string;
    endDate?: string;
  },
  options?: { [key: string]: any },
) {
  return request<{
    code: number;
    message: string;
    data: GamePlatform.WithdrawalRecord[];
  }>('/verification/admin/transfer/pending', {
    method: 'GET',
    params: {
      ...params,
    },
    ...(options || {}),
  });
}

/** 审核提现申请 POST /verification/admin/transfer/review */
export async function reviewWithdrawal(
  transferId: string,
  body: {
    action: 'APPROVE' | 'REJECT';
    rejectReason?: string;
  },
  options?: { [key: string]: any }
) {
  // 转换为后端期望的格式
  const reviewData = {
    transferId: transferId,
    status: body.action === 'APPROVE' ? 'SUCCESS' : 'FAIL',
    reason: body.rejectReason || ''
  };

  return request<{
    code: number;
    message: string;
    data: string;
  }>('/verification/admin/transfer/review', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    data: reviewData,
    ...(options || {}),
  });
}

/** 获取提现申请详情 GET /verification/admin/transfer/{transferId} */
export async function getWithdrawalDetail(
  transferId: string,
  options?: { [key: string]: any }
) {
  return request<{
    code: number;
    message: string;
    data: GamePlatform.WithdrawalRecord;
  }>(`/verification/admin/transfer/${encodeURIComponent(transferId)}`, {
    method: 'GET',
    ...(options || {}),
  });
}

/** 批量处理提现 - 暂不支持 */
export async function batchProcessWithdrawals(
  body: {
    transferIds: string[];
    action: 'APPROVE' | 'REJECT';
    rejectReason?: string;
  },
  options?: { [key: string]: any }
) {
  // 批量处理可以通过循环调用单个审核接口实现
  const results = [];
  for (const transferId of body.transferIds) {
    try {
      const result = await reviewWithdrawal(transferId, {
        action: body.action,
        rejectReason: body.rejectReason
      });
      results.push({ transferId, success: result.code === 200 });
    } catch (error) {
      results.push({ transferId, success: false });
    }
  }
  
  const successCount = results.filter(r => r.success).length;
  return Promise.resolve({
    code: 200,
    message: `批量处理完成，成功处理 ${successCount}/${body.transferIds.length} 条记录`,
    data: { processedCount: successCount }
  });
}

// ============= 用户管理 =============

/** 获取用户列表 GET /admin/users */
export async function getUsers(
  params: {
    page?: number;
    size?: number;
    keyword?: string;
    isTrainer?: boolean;
    verified?: boolean;
  },
  options?: { [key: string]: any },
) {
  return request<GamePlatform.PaginatedResponse<GamePlatform.User>>('/admin/users', {
    method: 'GET',
    params: {
      ...params,
    },
    ...(options || {}),
  });
}

/** 获取用户详情 GET /admin/users/{id} */
export async function getUserDetail(
  id: number,
  options?: { [key: string]: any }
) {
  return request<{
    success: boolean;
    data: GamePlatform.User;
  }>(`/admin/users/${id}`, {
    method: 'GET',
    ...(options || {}),
  });
}

// ============= 系统统计 =============

/** 获取系统统计数据 GET /admin/statistics */
export async function getSystemStatistics(options?: { [key: string]: any }) {
  return request<{
    success: boolean;
    data: GamePlatform.SystemStatistics;
  }>('/admin/statistics', {
    method: 'GET',
    ...(options || {}),
  });
}
